﻿using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Diagnostics;
using System.Collections.Generic;
namespace BingImageManager
{
    internal class BingApi
    {
        public static readonly String[] LocationOptions = { "en-US", "zh-CN", "ja-JP", "en-AU", "de-DE", "en-NZ", "en-CA" };
        private const String BingUrl = "http://www.bing.com";
        private const String ApiUrlBase = BingUrl + "/HPImageArchive.aspx";

        //对应API中的idx参数，表示时间，-1为明天，1为昨天，2为后天，依次类推，已知可选项-1 ~ 18，默认为0
        public Int32 Time = 0;
        //对应API中的mkt参数，表示地区，可选项见LocationOptions，如果为null或空字符串则随机从LocationOptions中选择一个，默认为null
        public String Location = null;

        private String _apiUrl;
        private String _defaultImageUrl;
        private String _imageUrlBase;
        private Action _downloadAction;
        public void Init(Action downloadAction)
        {
            this._downloadAction = downloadAction;
            Refresh();
        }
        public void Refresh()
        {
            InitApiUrl();
            Debug.WriteLine("开始请求BingApi:" + _apiUrl);
            HttpWebRequest request =(HttpWebRequest)HttpWebRequest.Create(_apiUrl);
            request.BeginGetResponse(GetAvatarImageCallback, request);
        }
        void GetAvatarImageCallback(IAsyncResult result)
        {
            HttpWebRequest request = result.AsyncState as HttpWebRequest;
            if (request != null)
            {
                try
                {
                    string resultStr;
                    using (WebResponse response = request.EndGetResponse(result))
                    {
                        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                        {
                            resultStr = sr.ReadToEnd();
                        }
                    }
                    Debug.WriteLine("请求BingApi成功");
                    ParseResponse(resultStr);

                }
                catch (WebException e)
                {
                    Debug.WriteLine("请求BingApi失败" + e.ToString());
                    return;
                }
            }
        }
        private void ParseResponse(String res)
        {
            Debug.WriteLine("开始解析BingApi返回值..." );

            try
            {
                XDocument loadedData = XDocument.Parse(res, LoadOptions.None);
                List<BingImage> bingImgs = (from query in loadedData.Descendants("image")
                                            select new BingImage
                                            {
                                                url = (string)query.Element("url"),
                                                urlBase = (string)query.Element("urlBase")
                                            }).ToList<BingImage>();
                if (bingImgs == null || bingImgs.Count < 1) return;
                _defaultImageUrl = BingUrl + bingImgs[0].url;
                _imageUrlBase = BingUrl + bingImgs[0].urlBase;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            Debug.WriteLine("解析BingApi返回值成功");
            this._downloadAction.Invoke();
        }

        private void InitApiUrl()
        {
            if (String.IsNullOrEmpty(Location))
            {
                int randIndex = new Random().Next(0, LocationOptions.Length);
                Location = LocationOptions[randIndex];
            }
            _apiUrl = ApiUrlBase + "?/format=xml&n=1&idx=" + Time + "&mkt=" + Location;
        }


        /// <summary>
        /// 获取图片的地址，如果resolution为null或空字符串将返回默认url
        /// 指定resolution后的地址可能不存在
        /// resolution已知可选项有640x480,800x600,1024x768,1280x720,1920x1080,800x480,1366x768,1920x1200,1280x768
        /// </summary>
        public String GetImageUrl(String resolution = null)
        {
            if (String.IsNullOrEmpty(resolution))
            {
                return _imageUrlBase + "_" + "480x800" + ".jpg"; ;
            }
            return _imageUrlBase + "_" + resolution + ".jpg";
        }

    }
}
